package com.clockey.server.util;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class HttpClientUtil {

	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	public static final String CONTENT_TYPE_JSON = "application/json";
	public static final String CONTENT_TYPE_XML = "text/xml";

	/**
	 * 测试服务接口,传输json格式
	 * 
	 * @param requestUrl
	 * @param requestMap
	 * @return
	 */
	public static String sendRequest(String requestUrl, Map<String, Object> requestMap) {
		String requestJson = JSON.toJSONString(requestMap);
		return sendRequest(requestUrl, requestJson, CONTENT_TYPE_JSON);
	}

	/**
	 * 传输内容
	 * @param requestUrl
	 * @param requestContent string格式的内容
	 * @param contentType application/json或text/xml
	 * @return
	 */
	public static String sendRequest(String requestUrl, String requestContent, String contentType) {
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(requestUrl);
		postMethod.setRequestHeader("Connection", "close");

		String responseStr = null;
		try {
			postMethod.setRequestEntity(new StringRequestEntity(requestContent, contentType, "utf-8"));
			httpClient.executeMethod(postMethod);
			responseStr = postMethod.getResponseBodyAsString();
		} catch (HttpException e) {
			logger.info("http error1: ", e);
		} catch (IOException e) {
			logger.info("http error2: ", e);
		} catch (Exception e) {
			logger.info("http error3: ", e);
		} finally {
			postMethod.releaseConnection();
		}
		return responseStr;
	}

}
